package com.zhz.mutil.infras.repository.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhz.mutil.domain.contract.dto.DbDataSourceDTO;
import com.zhz.mutil.infras.repository.mapper.DbSourceConfigMapper;
import com.zhz.mutil.infras.repository.entity.DbSourceConfig;
import com.zhz.mutil.infras.repository.service.DbSourceConfigService;
import com.zhz.mutil.infras.utils.DbOprUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 数据库配置(DbSourceConfig)表服务实现类
 *
 * @author zhouhengzhe
 * @since 2024-10-15 16:45:06
 */
@Service
public class DbSourceConfigServiceImpl extends ServiceImpl<DbSourceConfigMapper, DbSourceConfig> implements DbSourceConfigService {

    @Autowired
    private DbOprUtil dbOprUtil;

    /**
     * 新增数据源
     *
     * @param form
     */
    @Override
    public void add(DbDataSourceDTO form) {
        dbOprUtil.changeByDataSourceByName("master");
        this.save(DbSourceConfig
                .builder()
                .url(form.getUrl())
                .username(form.getUsername())
                .password(form.getPassword())
                .driverClassName(form.getDriverClassName())
                .type(form.getType())
                .poolName(form.getPoolName())
                .build());
    }

    /**
     * 修改数据源
     *
     * @param form
     */
    @Override
    public void modify(DbDataSourceDTO form) {
        dbOprUtil.changeByDataSourceByName("master");
        DbSourceConfig dbSourceConfig = this.getOne(Wrappers
                .lambdaQuery(DbSourceConfig.class)
                .eq(DbSourceConfig::getPoolName, form.getPoolName()));
        if (dbSourceConfig != null) {
            dbSourceConfig.setUrl(form.getUrl());
            dbSourceConfig.setUsername(form.getUsername());
            dbSourceConfig.setPassword(form.getPassword());
            dbSourceConfig.setDriverClassName(form.getDriverClassName());
            dbSourceConfig.setType(form.getType());
            this.updateById(dbSourceConfig);
        }
    }

    /**
     * 删除数据源
     *
     * @param form
     */
    @Override
    public void delete(DbDataSourceDTO form) {
        dbOprUtil.changeByDataSourceByName("master");
        DbSourceConfig dbSourceConfig = this.getOne(Wrappers
                .lambdaQuery(DbSourceConfig.class)
                .eq(DbSourceConfig::getPoolName, form.getPoolName()));
        if (dbSourceConfig != null) {
            this.removeById(dbSourceConfig.getId());
        }
    }
}

